﻿namespace KeppelLand.Controllers
{
    using KeppelLand.Entities;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;


    /// <summary>   
    /// Summary description for ApplicationSettingController
    /// </summary>
    public class ApplicationSettingController
    {
        public ApplicationSettingController()
        {
        }

        public static ApplicationSetting GetApplicationSetting(string name)
        {
            ApplicationSetting applicationSetting = null;

            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EOCS"].ConnectionString))
            {
                DataSet ds = new DataSet();
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "SELECT * FROM ApplicationSetting WHERE Name = @Name;";
                cmd.Parameters.AddWithValue("@Name", name);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);

                if ((ds.Tables.Count > 0) && (ds.Tables[0].Rows.Count > 0))
                {
                    applicationSetting = ds.Tables[0].AsEnumerable().Select(r => new ApplicationSetting
                    {
                        Id = r.Field<int>("Id"),
                        Name = r.Field<string>("Name"),
                        Value = r.Field<string>("Value"),
                        ModifiedDateTime = r.Field<DateTime?>("ModifiedDateTime")
                    }).FirstOrDefault();
                }
            }

            return applicationSetting;
        }

        public static void SetApplicationSetting(ApplicationSetting applicationSetting)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EOCS"].ConnectionString))
            {
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = @"UPDATE  ApplicationSetting 
SET     Name = @Name,
        Value = @Value,
        ModifiedDateTime = @ModifiedDateTime
WHERE   Id = @Id;";

                cmd.Parameters.AddWithValue("@Id", applicationSetting.Id);
                cmd.Parameters.AddWithValue("@Name", applicationSetting.Name);
                cmd.Parameters.AddWithValue("@Value", applicationSetting.Value);
                cmd.Parameters.AddWithValue("@ModifiedDateTime", applicationSetting.ModifiedDateTime);

                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }
    }
}